import {
  getConfig,
  userCollection
} from '../share/index'

import getValidInviteCode from './get-valid-Invite-code'

export default async function (user) {
  let result
  const {
    my_invite_code: inviteCode
  } = user
  const config = getConfig()
  if (!config.autoSetInviteCode && !inviteCode) {
    result = await userCollection.add(user)
    return {
      code: 0,
      msg: '注册成功',
      result
    }
  }
  const validResult = await getValidInviteCode({
    inviteCode
  })
  if (validResult.code > 0) {
    return validResult
  }
  user.my_invite_code = validResult.inviteCode
  result = await userCollection.add(user)
  return {
    code: 0,
    msg: '邀请码设置成功',
    result
  }
}
